//
//  AppDelegate.swift
//  XMPPTest
//
//  Created by 陈学明 on 17/2/9.
//  Copyright © 2017年 muxue. All rights reserved.
//

import UIKit
import XMPPFramework
@UIApplicationMain


class AppDelegate: UIResponder, UIApplicationDelegate,XMPPStreamDelegate {

    var window: UIWindow?
    var queue:DispatchQueue? = nil
    var xmppStream:XMPPStream? = nil
    var isRegist:Bool = false
    var loginRegistDelegate:LoginRegistDelagate?
    var rosterListDelegate:RosterListDelegate?
    var rosterStorage:XMPPRosterCoreDataStorage?
    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        connect(isRegist: false)
        window?.rootViewController = MXNavVC(rootViewController: MXLoginRegistVC())
        return true
    }

    func strupStream(){
        queue = DispatchQueue.main
        xmppStream = XMPPStream()
        xmppStream?.addDelegate(self, delegateQueue: queue)
    }

    func connect(isRegist:Bool) -> Bool {
        self.strupStream()
        let defaults = UserDefaults.standard
        let userName = defaults.object(forKey: "USERNAME")
        let passWord = defaults.object(forKey: "PASSWORD")
        let server = defaults.object(forKey: "SERVER_KEY")
        // 如果已经建立了连接，先断开连接
        if (xmppStream?.isConnected())! {
            self.goOnline()
            xmppStream?.disconnect()
        }
        if userName == nil || passWord == nil {
            return false
        }
        self.isRegist = isRegist
        
        xmppStream?.hostName = (server as! String)
        xmppStream?.myJID = XMPPJID(string: (userName as! String) + "@muxue.local")
        
        
        do{
        try xmppStream?.connect(withTimeout: 10)
            return true
        }catch{
            return false
        }
        
    }
    //底层socket连接成功
    func xmppStream(_ sender: XMPPStream!, socketDidConnect socket: GCDAsyncSocket!) {
        print("底层socket连接成功")
    }
    //xmppstream连接成功
    func xmppStreamDidConnect(_ sender: XMPPStream!) {
        print("xmppstream连接成功")
        
        let defaults = UserDefaults.standard
        let passWord = defaults.object(forKey: "PASSWORD") as! String!
        if passWord == nil || passWord?.utf8.count==0 {
            self.loginRegistDelegate?.showAlert(title: "用户没有输入有效的密码")
            return;
        }
        
        if isRegist {
            //注册
            try! self.xmppStream?.register(withPassword: passWord)
            
        }else{
            //登录
            try! self.xmppStream?.authenticate(withPassword: passWord)
        }
        
    }
    //xmppstream连接超时
    func xmppStreamConnectDidTimeout(_ sender: XMPPStream!) {
        print("xmppstream连接超时")
    }
    
    // 登录成功
    func xmppStreamDidAuthenticate(_ sender: XMPPStream!) {

        self.loginRegistDelegate?.showAlert(title: "登录成功")
        self.goOffline()
        window?.rootViewController = MXBarVC()
    }
    //登录失败
    func xmppStream(_ sender: XMPPStream!, didNotAuthenticate error: DDXMLElement!) {
        self.loginRegistDelegate?.showAlert(title: "登录失败")
    }
    //注册成功
    func xmppStream(_ sender: XMPPStream!, didRegisterModule module: Any!) {

        self.loginRegistDelegate?.showAlert(title: "注册成功")
        window?.rootViewController = MXBarVC()
    }
    //注册失败
    func xmppStream(_ sender: XMPPStream!, didNotRegister error: DDXMLElement!) {

        self.loginRegistDelegate?.showAlert(title: "注册失败")
    }
    
    func goOnline() {
        //发送在线状态
        let presence = XMPPPresence()
        self.xmppStream?.send(presence)
        
    }
    func goOffline(){
        let presence = XMPPPresence(type: "unailable")
        self.xmppStream?.send(presence)
        
    }
}
protocol LoginRegistDelagate {
    func showAlert(title:String)->()
}

protocol RosterListDelegate {
    
}
